package com.guotd.ticketSystem.controller;

import com.guotd.ticketSystem.entity.*;
import com.guotd.ticketSystem.mapper.OrderMapper;
import com.guotd.ticketSystem.utils.RandomUtil;
import com.guotd.ticketSystem.utils.SessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;

@WebServlet("/orderSubmit")
public class OrderSubmitServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = RandomUtil.getRandomNum();
        String userId = request.getParameter("userId");
        User user = new User();
        user.setId(userId);
        String passengerId = request.getParameter("identity");
        String passengerName = request.getParameter("name");
        String passengerPhone = request.getParameter("phone");
        Date passengerBir = Date.valueOf(request.getParameter("birthday"));
        Passenger passenger = new Passenger(passengerId, passengerName, passengerPhone, passengerBir);
        String flightId = request.getParameter("flightId");
        Flight flight = new Flight();
        flight.setId(flightId);
        String cabinId = request.getParameter("cabinId");
        Cabin cabin = new Cabin();
        cabin.setId(cabinId);
        Order order = new Order(id,user,passenger,flight,cabin,1);
        try {
            SqlSession session = SessionUtil.getSqlSession();
            OrderMapper orderMapper = session.getMapper(OrderMapper.class);
            orderMapper.p2(order);
            int row = orderMapper.addOrder(order);
            session.commit();
            session.close();
            if (row > 0) {
                request.setAttribute("userId", userId);
                request.getSession().setAttribute("order_msg", "订单提交成功！");
                request.getRequestDispatcher("orderSelect").forward(request, response);
            }
        }catch (Exception e){
            request.setAttribute("order_msg", "订单提交失败!");
            request.getRequestDispatcher("order_submit.jsp").forward(request, response);
        }
    }
}